package com.math.aistudykbr.service.impl;

import com.math.aistudykbr.constant.MessageConstants;
import com.math.aistudykbr.service.BaiduOCRService;
import com.math.aistudykbr.utils.BaiduOcrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;

@Service
@Slf4j
@RequiredArgsConstructor
public class BaiduOCRServiceImpl implements BaiduOCRService {

    private final BaiduOcrUtil baiduOcrUtil;

    @Override
    public ArrayList<String> imageToFont(MultipartFile image) throws IOException {
        if (!baiduOcrUtil.isImage(image.getInputStream())) {
            throw new IllegalArgumentException(MessageConstants.NotImage);
        }

        String path = saveTempFile(image);
        ArrayList<String> result = baiduOcrUtil.basicGeneral(path);
        deleteTempFile(path);

        return result;
    }

    private String saveTempFile(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String path = "./" + fileName;
        file.transferTo(Path.of(path));
        log.info("Saved temporary file: {}", path);
        return path;
    }

    private void deleteTempFile(String path) {
        try {
            File file = new File(path);
            if (file.exists()) {
                boolean deleted = file.delete();
                if (deleted) {
                    log.info("Deleted temporary file: {}", path);
                } else {
                    log.warn("Failed to delete temporary file: {}", path);
                }
            }
        } catch (Exception e) {
            log.error("Error deleting temporary file: {}", path, e);
        }
    }
}
